import json
import os
import re
from typing import Dict, List, Union

def format_code_block(language: str, content: str) -> str:
    """
    Format a code block with proper syntax highlighting
    
    Args:
        language: Programming language for syntax highlighting
        content: Code content
        
    Returns:
        Formatted code block string
    """
    return f"```{language}\n{content}\n```"

def format_inline_code(language: str, content: str) -> str:
    """
    Format inline code with proper syntax highlighting
    
    Args:
        language: Programming language for syntax highlighting
        content: Code content
        
    Returns:
        Formatted inline code string
    """
    return f"`{content}`"

def format_image(image_data: Dict) -> str:
    """
    Format an image with alt text and optional title
    
    Args:
        image_data: Dictionary containing image information
        
    Returns:
        Formatted image string
    """
    alt_text = image_data.get("alt", "Image")
    url = image_data.get("url", "")
    title = image_data.get("title", "")
    
    if title:
        return f"![{alt_text}]({url} \"{title}\")"
    return f"![{alt_text}]({url})"

def format_link(link_data: Dict) -> str:
    """
    Format a link with optional description
    
    Args:
        link_data: Dictionary containing link information
        
    Returns:
        Formatted link string
    """
    text = link_data.get("text", "")
    link = link_data.get("link", "")
    description = link_data.get("description", "")
    
    if description:
        return f"[{text}]({link}) - {description}"
    return f"[{text}]({link})"

def process_mixed_content(content: Union[str, Dict, List]) -> str:
    """
    Process content that may contain both regular text and code blocks
    
    Args:
        content: Content to process (string, dictionary, or list)
        
    Returns:
        Processed content string
    """
    if isinstance(content, str):
        return content
    elif isinstance(content, dict):
        # 检查是否是代码块
        if "type" in content and content["type"] == "code":
            language = content.get("language", "")
            code_content = content.get("content", "")
            # 如果是单行代码，使用行内代码格式
            if "\n" not in code_content:
                return format_inline_code(language, code_content)
            return format_code_block(language, code_content)
        # 检查是否是图片
        elif "type" in content and content["type"] == "image":
            return format_image(content)
        # 检查是否是链接
        elif "link" in content:
            return format_link(content)
        # 处理普通内容
        return content.get("text", str(content))
    elif isinstance(content, list):
        # 处理列表内容
        result = []
        for item in content:
            processed = process_mixed_content(item)
            if processed:
                result.append(processed)
        return "".join(result)
    return str(content)

def process_items(items: List[Union[str, Dict]]) -> str:
    """
    Process a list of items that may contain code blocks, links, or other content
    
    Args:
        items: List of items to process
        
    Returns:
        Formatted items string
    """
    result = []
    for item in items:
        if isinstance(item, dict):
            if "type" in item:
                if item["type"] == "code":
                    language = item.get("language", "")
                    code_content = item.get("content", "")
                    # 如果是单行代码，使用行内代码格式
                    if "\n" not in code_content:
                        result.append(f"- {format_inline_code(language, code_content)}")
                    else:
                        result.append(format_code_block(language, code_content))
                elif item["type"] == "image":
                    result.append(f"- {format_image(item)}")
            elif "link" in item:
                result.append(f"- {format_link(item)}")
            else:
                result.append(f"- {process_mixed_content(item)}")
        else:
            result.append(f"- {process_mixed_content(item)}")
    return "\n".join(result) + "\n"

def process_code_example(code_example: Dict) -> str:
    """
    Process a code example
    
    Args:
        code_example: Code example dictionary
        
    Returns:
        Formatted code example string
    """
    if not isinstance(code_example, dict):
        return str(code_example)
        
    if "code" in code_example:
        code_data = code_example["code"]
        language = code_data.get("language", "")
        code_content = code_data.get("content", "")
        return format_code_block(language, code_content)
    elif "type" in code_example and code_example["type"] == "code":
        language = code_example.get("language", "")
        code_content = code_example.get("content", "")
        return format_code_block(language, code_content)
    return str(code_example)

def json_to_markdown(data: Union[Dict, List], heading_level: int = 1) -> str:
    """
    Convert JSON source to Markdown format with support for code blocks, images, and hyperlinks
    
    Args:
        data: JSON source (dict or list)
        heading_level: Current heading level (1-6)
        
    Returns:
        str: Markdown formatted string
    """
    markdown = ""
    
    if isinstance(data, dict):
        # 处理文档标题和介绍
        if "title" in data and "content" in data:
            # 添加主标题
            markdown += f"# {data['title']}\n\n"
            
            # 处理内容部分
            content = data["content"]
            if isinstance(content, dict):
                # 处理介绍
                if "introduction" in content:
                    markdown += f"{process_mixed_content(content['introduction'])}\n\n"
                
                # 处理章节
                if "sections" in content:
                    for section in content["sections"]:
                        if isinstance(section, dict):
                            # 添加章节标题
                            if "title" in section:
                                markdown += f"## {section['title']}\n\n"
                            
                            # 处理章节内容
                            if "content" in section:
                                markdown += f"{process_mixed_content(section['content'])}\n\n"
                            
                            # 处理图片
                            if "image" in section:
                                markdown += f"{format_image(section['image'])}\n\n"
                            
                            # 处理代码示例
                            if "code_example" in section:
                                markdown += f"{process_code_example(section['code_example'])}\n\n"
                            
                            # 处理子章节
                            if "subsections" in section:
                                for subsection in section["subsections"]:
                                    if isinstance(subsection, dict):
                                        # 添加子章节标题
                                        if "title" in subsection:
                                            markdown += f"### {subsection['title']}\n\n"
                                        
                                        # 处理子章节内容
                                        if "content" in subsection:
                                            markdown += f"{process_mixed_content(subsection['content'])}\n\n"
                                        
                                        # 处理子章节图片
                                        if "image" in subsection:
                                            markdown += f"{format_image(subsection['image'])}\n\n"
                                        
                                        # 处理子章节的代码示例
                                        if "code_example" in subsection:
                                            markdown += f"{process_code_example(subsection['code_example'])}\n\n"
                                        
                                        # 处理子章节的列表项
                                        if "items" in subsection:
                                            markdown += process_items(subsection["items"]) + "\n"
    
    return markdown

def save_json_to_markdown(json_data: Union[Dict, List], output_file: str) -> None:
    """
    Save JSON source to a Markdown file
    
    Args:
        json_data: JSON source to convert
        output_file: Path to the output Markdown file
    """
    markdown = json_to_markdown(json_data)
    
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(markdown)

def load_json_from_file(file_path: str) -> Union[Dict, List]:
    """
    Load JSON source from a file
    
    Args:
        file_path: Path to the JSON file
        
    Returns:
        Union[Dict, List]: Loaded JSON source
    """
    with open(file_path, 'r', encoding='utf-8') as f:
        return json.load(f)

def main():
    # 从JSON文件加载数据
    json_data = load_json_from_file('chat_client_api.json')
    
    # 转换为Markdown并保存
    save_json_to_markdown(json_data, "chat_client_api.md")
    print("Markdown file has been created successfully!")

if __name__ == "__main__":
    main() 